package com.egoonet.web;

import com.egoonet.dao.PostRepository;
import com.egoonet.dao.projections.PostIdAndTitle;
import com.egoonet.domain.Post;
import com.github.wenhao.jpa.Specifications;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 *
 * Created by wchi on 2017/4/20.
 */
@RestController
public class PostController {
    @Autowired
    PostRepository postRepository;

    @RequestMapping(value="/post/username/{userName}", method = RequestMethod.GET)
    public List<Post> queryPost(@PathVariable("userName") String userName){
       List<Post> postList = postRepository.findByCreator_UserName(userName);
       return postList;
    }

    @RequestMapping(value="/post/joinquery", method = RequestMethod.GET)
    public List<Post> queryPostWithMultiCondition(@RequestParam("userName") String userName, @RequestParam("isdn") Integer isdn){
        List<Post> postList = postRepository.findByCreator_UserNameAndIsdnGreaterThan(userName, isdn);
        return postList;
    }

    @RequestMapping(value="/post/titlelike/{title}", method = RequestMethod.GET)
    public List<Post> queryPostByLike(@PathVariable("title") String title){
        List<Post> postList = postRepository.findByTitleLike(title);
        return postList;
    }

    @RequestMapping(value="/post/titlecontain/{title}", method = RequestMethod.GET)
    public List<Post> queryPostByContain(@PathVariable("title") String title){
        List<Post> postList = postRepository.findByTitleContaining(title);
        return postList;
    }

    @RequestMapping(value="/post/dynamicquery", method = RequestMethod.GET)
    public List<Post> queryDynamicParam(@RequestParam("title") String title, @RequestParam("isdn") Integer isdn){
        Specification<Post> specification = Specifications.<Post>and()
                .eq(!Strings.isNullOrEmpty(title), "title", title)
                .eq(isdn!=null, "isdn", isdn)
                .build();
        List<Post> postList = postRepository.findAll(specification);
        return postList;
    }

    /**
     * 测试使用projections来进行查询结果列的筛选
     * @return
     */
    @RequestMapping(value="/post/alltitleandid", method = RequestMethod.GET)
    public List<PostIdAndTitle> getAllTitleAndId(){
        List<PostIdAndTitle> list = postRepository.findAllIdAndTitle();
        return list;
    }

    @RequestMapping(value="/post/projectionsbyisdn", method = RequestMethod.GET)
    public List<PostIdAndTitle> getAllTitleAndId(@RequestParam("isdn") Integer isdn){
        List<PostIdAndTitle> list = postRepository.findByIsdn(isdn);
        return list;
    }
}
